
#include "vectornameserver.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <utility>
#include <stdlib.h>

using namespace std;

namespace cpp_lab4 {

   //typedef pair<HostName, IPAddress> dns_record;

    void VectorNameServer::insert(const HostName& host, const IPAddress& ip) {
    	pair <string,int> pair;
    	pair = make_pair(host, ip);
        database.push_back(pair);
    }

    // functor
    /*
    struct first_equal : public binary_function<pair<string, int>&, HostName& hn, bool> {

    	bool operator() (const pair<string, int>& pair) const
    	   {
    	    	return (pair.first == hn);
    	   }

        //bool operator() (const string* p, const HostName* s) const {
        //    return p.first == s;
        //}
    };
    */

    struct first_equal : public binary_function<pair<string, int>, string, bool> {
    	bool operator() (const pair<string, int>& pair,const HostName& n) const {
    	    return pair.first == n;
    	}
    };

    /*
     * Remove the pair with the specified host name. Returns true
     * if the host name existed and the pair was removed, false
     * otherwise.
     */
    bool VectorNameServer::remove(const HostName& name) {
        vector<	pair<string,int> >::iterator result;
        result = find_if(database.begin(), database.end(), bind2nd(first_equal(), name));

        if (result != database.end()) {
            database.erase(result);
            return true;
        } else {
            return false;
        }
    }

    /*
     * Find the IP address for the specified host name. Returns
     * NON_EXISTING_ADDRESS if the host name wasn't in the name
     * server.
     */
    IPAddress VectorNameServer::lookup(const HostName& name) const {
        vector< pair<string,int> >::const_iterator result;
        result = find_if(database.begin(), database.end(), bind2nd(first_equal(), name));

        if (result != database.end()) {
            //return database.at(result).second;
            return result->second;
        } else {
            return NON_EXISTING_ADDRESS;
        }
    }
}

